package org.liveboardgames.agricola.control.delegates
{
    import com.adobe.cairngorm.business.ServiceLocator;
    
    import mx.collections.ListCollectionView;
    import mx.rpc.IResponder;
    
    import org.liveboardgames.agricola.model.AgricolaModelLocator;
    import org.liveboardgames.agricola.vo.farm.FarmElement;
    import org.liveboardgames.agricola.vo.farm.FarmTile;
    import org.liveboardgames.agricola.vo.player.Player;
    import org.liveboardgames.common.dictionary.collections.IMap;
    
    public class HarvestFieldDelegate
    {
        private var _responder:IResponder;
        
        private var _service:Object;
        
        public function HarvestFieldDelegate(responder:IResponder)
        {
            this._service = ServiceLocator.getInstance().getRemoteObject( "harvestService" );
            this._responder = responder;
        }
        
        public function harvestField(player:Player):void
        {
        	var call:Object = _service.harvestField(AgricolaModelLocator.getInstance().game.id, player.id);
			call.resultHandler = _responder.result;
			call.faultHandler = _responder.fault;
//            setTimeout(harvestFieldService, 0, player);
        }
        
        private function harvestFieldService(player:Player):void
        {
            var tiles:ListCollectionView = player.farm.tiles;
            
            for each (var tile:FarmTile in tiles)
            {
                var farmElement:String = tile.farmElement;
                if (farmElement == FarmElement.FIELD)
                {
                    var resourcesOnTile:IMap = tile.resources;
                    if (resourcesOnTile != null)
                    {
                        var resourceTypes:ListCollectionView = resourcesOnTile.getKeys();
                        if (resourceTypes != null)
                        {
                            for each (var resourceType:String in resourceTypes)
                            {
                                var quantity:int = resourcesOnTile.getValue(resourceType);
                                
                                // Take one resource from the field
                                var newQuantity:int = quantity - 1;
                                resourcesOnTile.put(resourceType, newQuantity);
                                
                                // And add it to the stock
                                player.farm.addResource(resourceType, 1);
                            }
                        }
                    }
                }
            }
            
            AgricolaModelLocator.getInstance().game.harvestFieldPlayers.addItem(player);
        }
    }
}